#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sched.h>
#include <sys/time.h>

#define INITIAL_DATA 0

typedef struct
{
	int data;
	double init_time;
} thread_arg_t;

typedef void* (*void_f)(void*);

void_f check(void* arg)
{
	thread_arg_t *theArg = (thread_arg_t *) arg;
	struct timeval tv;
	
	while (theArg->data == INITIAL_DATA)
	{
		sched_yield();
		
		gettimeofday(&tv, NULL);
		if (tv.tv_sec > theArg->init_time + 1.0)
		{
			printf("Timeout -- pretty sure your CPU doesn't have cache coherence!\n");
			pthread_exit(NULL);
		}
	}
	
	printf("Cache has updated -- you have cache coherence!\n");
	pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
	thread_arg_t arg =
	{
		data:INITIAL_DATA
	};
	
	pthread_t checker_thread;
	
	struct timeval tv;
	gettimeofday(&tv, NULL);
	arg.init_time = tv.tv_sec+(tv.tv_usec/1000000);
	
	if (pthread_create(&checker_thread, NULL, check, &arg))
	{
		printf("Thread creation error\n");
		abort();
	}
	
	arg.data = 10;
	
	pthread_join(checker_thread, NULL);
	
	gettimeofday(&tv, NULL);
	printf("Time elapsed: %f\n", (tv.tv_sec+(tv.tv_usec/1000000)) - arg.init_time);
	
	return 0;
}
